var express = require('express')
var router = express.Router()
const {success, error} = require("../../utils/message");
const models = require("../../models");
const bcrypt = require("bcryptjs");

// 后台首页
router.get('/', function (req, res, next) {
    success(res, '欢迎来到长乐健康后台管理系统', '123')
})

// 修改密码
router.put('/', async function (req, res, next) {
    const password = req.body.password
    const checkPassword = req.body.checkPassword
    const oldPassword = req.body.oldPassword

    const passwordRes = bcrypt.compareSync(oldPassword, req.decoded.user.password)
    if (!passwordRes) {
        return error(res, '旧密码填写错误')
    }

    if (!(password || checkPassword)) {
        return error(res, '新密码和确认密码必须填写！')
    }

    if (password !== checkPassword) {
        return error(res, '两次新密码输入不一致！')
    }

    // 生成盐
    const salt = bcrypt.genSaltSync(10)

    // 对用户填写的密码进行加密
    const hash = bcrypt.hashSync(password.toString(), salt)

    const user = await models.User.findOne({where: {id: req.decoded.user.id}})
    // 用户数据
    const body = {
        password: hash,
        admin: true,
    }

    user.update(body)
    return success(res, '修改成功，请重新登录', {user})
})

module.exports = router
